package com.yangrong.thread.chapter5;

/**
 * 公共资源 SharedResource
 * 
 * pass写操作与toString读操作在一起也存在线程安全问题
 * 
 * @author YangRong
 * @date 2020年6月8日
 */
public class Gate {

	private int counter = 0;
	private String name = "Nobody";
	private String address = "Nowhere";

	/**
	 * 临界值
	 * 
	 * @param name
	 * @param address
	 */
	public synchronized void pass(String name, String address) {
		this.counter++;
		/* race */
		this.name = name;
		this.address = address;
		verify();
	}

	private void verify() {
		if (this.name.charAt(0) != this.address.charAt(0)) {
			System.out.println("******BROKEN******" + toString());
		}
	}

	public synchronized String toString() {
		return "No." + counter + ":" + name + "," + address;
	}

}
